package com.mango.community.service;

import com.mango.community.dao.CommentMapper;
import com.mango.community.entity.Comment;
import com.mango.community.util.CommunityConstant;
import com.mango.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/26 21:17
 */
@Service
public class CommentService implements CommunityConstant {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private DiscussPostService discussPostService;

    /**  查询评论的集合
     * @param entityType
     * @param entityId
     * @param offset
     * @param limit
     * @return
     */
    public List<Comment> findCommentByEntity(int entityType ,int entityId,int offset,int limit){
        return commentMapper.selectCommentByEntity(entityType, entityId, offset, limit);
    }

    /** 查询评论的总数
     * @param entityType
     * @param entityId
     * @return
     */
    public int findCommentCount(int entityType ,int entityId){
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    /** 增加评论
     * @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
     * isolation 定义事务的隔离级别  propagation 定义事务的传播级别
     * @param comment
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if (comment == null ){
            throw new IllegalArgumentException("参数不能为空！");
        }
        //添加评论
        //过滤html标签
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        //过滤敏感词
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);
        //更新帖子的评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST){
            //查询出评论的数量
           int count= commentMapper.selectCountByEntity(comment.getEntityType(),comment.getEntityId());
           //更新帖子的评论数量
           discussPostService.updateCommentCount(comment.getEntityId(),count);
        }
        return rows;
    }

    /** 根据评论id查询评论
     * @param id
     * @return
     */
    public Comment findCommentById(int id){
        return commentMapper.selectCommentById(id);
    }
}
